import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

/**
 * Main entry point for the Sudoku solving program
 * Parses input (into a 2D array) and uses it to create a Board
 * Prints out the solution (if solved, or current board with possible values for cells if not solved)
 * 
 * command line arg: java SudokuPuzzle puzzleInput.txt
 * 
 * @author Theresa Wellington
 * @date April 2013
 */
public class SudokuPuzzle {
	
	// the puzzle solver
	SudokuSolver sudokuSolver;
	
	/**
	 * Creates a SudokuPuzzle object
	 * @param boardInput the initial input sudoku puzzle
	 * @param boardSize the size of the puzzle - 
	 * criteria: boardSize % (int) Math.sqrt(boardSize) == 0
	 * example sizes: 4x4, 9x9, 16x16
	 */
	public SudokuPuzzle(int[][] boardInput, int boardSize){
		sudokuSolver = new SudokuSolver(new Board(boardInput, boardSize));
	}
	
	/**
	 * Calls sudokuSolver.solve() to solve the puzzle
	 * @return true if the puzzle is solved, else false
	 */
	public boolean solve(){
		return sudokuSolver.solve();
	}
	
	/**
	 * @return the puzzle im string form
	 */
	public String toString(){
		return sudokuSolver.printBoard();
	}
	
	
	public static void main(String[] args) throws FileNotFoundException{
		//Read input from a file
		Scanner scan =  new Scanner( new File (args[0]));
		String token = scan.next();
		//create a 2D array of boardSize x boardSize
		int  boardSize = Integer.parseInt(token);
		int[][] boardInput = new int[boardSize][boardSize];
		int colCount=0;
		int rowCount=0;
		
		//populate the board
		while (scan.hasNext()){
			token = scan.next();
			//ignore white space
			if(token == " " || token == "\n"){
					token = scan.next();
			}
			else{
				//parse String of ints and store in boardinput
				for(int i=0; i<Math.sqrt(boardSize); i++){
					String currentValue = token.charAt(i) + "";
					boardInput[rowCount][colCount] = Integer.parseInt(currentValue);
					colCount++;
				}				
				//handle end of current row
				if (colCount==boardSize){
					colCount = 0;
					rowCount++;
				}
			}
		}
		
		//create the puzzle
		SudokuPuzzle puzzle = new SudokuPuzzle(boardInput, boardSize);
		//output the puzzle
		System.out.println("Solved: " + puzzle.solve());
		System.out.println(puzzle.toString());
	}
	
	// Example input format:
	// 9
	//
	// 300 724 000
	// 025 000 000
	// 007 135 000
	//
	// 700 003 060
	// 801 060 407
	// 030 400 005
	//
	// 000 918 300
	// 000 000 970
	// 000 247 008
	
	// 4
	//
	// 40 10
	// 10 20
	//
	// 04 01
	// 01 02

}
